package com.ljx.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;
import com.ljx.entity.Student;
import com.ljx.entity.StudentExample;
import com.ljx.mapper.StudentMapper;
import com.ljx.service.StudentService;
import com.ljx.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nanhang.util.PageResult;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service(value = "StudentService")
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;
	
	
	public List<Student> findAll() {
		List<Student> students = studentMapper.selectByExample(null);
		System.out.println(students);
		return students;
	}
	
	public PageResult<Student> findByPage(Integer page, Integer pageSize) {
		// 1. 开始分页
		PageHelper.startPage(page, pageSize);

		// 2. 开始查询数据
		List<Student> students = this.findAll();

		// 3. 使用 PageInfo 来封装查询结果，获取分页信息
		PageInfo<Student> pageInfo = new PageInfo<>(students);

		// 4. 将查询结果和分页信息封装到 PageResult 中
		return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());

	}

	public PageResult<Student> search(Integer page, Integer pageSize, StudentVO studentVo) {
		// 1. 开始分页
		PageHelper.startPage(page, pageSize);
		// 2. 查询数据
		// 2.1 定义一次查询的实例
		StudentExample example = new StudentExample();
		// 2.2 添加查询条件到查询实例中
		StudentExample.Criteria criteria = example.createCriteria();
		if(StrUtil.isNotBlank(studentVo.getName())){
			criteria.andNameLike("%" + studentVo.getName() + "%");
		}

		if(studentVo.getAge() != null && studentVo.getAge() != 0){
			criteria.andAgeEqualTo(studentVo.getAge());
		}
		List<Student> students = studentMapper.selectByExample(example);
		// 2.4 将上面的students对象转换为List集合
		PageInfo<Student> pageInfo = new PageInfo<>(students);
		return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
		
	}
	
	// 3. 添加学生
	public boolean save(Student student) {
		return studentMapper.insert(student) > 0;
	}
}
